import React, { Component } from 'react'

import { Spring, config } from 'react-spring/renderprops'

import { API, getCurrentCity } from '../../../../utils'

// 导入三个子组件
import FilterTitle from '../FilterTitle'
import FilterPicker from '../FilterPicker'
import FilterMore from '../FilterMore'

import styles from './index.module.css'

export default class Filter extends Component {
  state = {
    // 标题高亮状态
    titleSelectedStatus: {
      area: false,
      mode: false,
      price: false,
      more: false
    },
    // 控制对话框的展示和隐藏
    // 使用一个状态，来控制两个对话框的展示和隐藏
    openType: '',
    // 筛选条件数据
    houseCoditions: {},
    // 所有筛选条件的选中值
    selectedValues: {
      area: ['area', 'null'],
      mode: ['null'],
      price: ['null'],
      more: []
    }
  }

  // 标题点击时，让对应的菜单高亮
  onTitleClick = type => {
    // 展示菜单栏，给父组件houseList添加overflow: hiden，以阻止列表滑动
    this.props.checkIsFixed(true)
    const { titleSelectedStatus, selectedValues } = this.state
    const newTitleSelectedStatus = {...titleSelectedStatus}
    Object.keys(titleSelectedStatus).forEach(item => {
      // console.log(item, type);
      // 点击菜单，让菜单高亮
      if (item === type) {
        newTitleSelectedStatus[item] = true
      } else {
        // 其他菜单如果有值则高亮，没有值不高亮
        const isChecked = this.checkTitleSelected(item, selectedValues[item])
        newTitleSelectedStatus[item] = isChecked
      }

    })
    this.setState({ titleSelectedStatus: newTitleSelectedStatus, openType: type})
  //   this.setState({
  //     titleSelectedStatus: {
  //       ...this.state.titleSelectedStatus,
  //       [type]: true
  //     },
  //     // 控制对话框的展示和隐藏
  //     openType: type
  //   })
  // }
  }
  // 点击取消，关闭对话框
  onClose = () => {
    // 关闭菜单栏，移除houseList的overflow: hiden，让房源列表可以滚动
    this.props.checkIsFixed(false)
    // this.setState({
    //   openType: ''
    // })
    // console.log(this.state.openType);
    const { openType, selectedValues, titleSelectedStatus } = this.state
    const isChecked = this.checkTitleSelected(openType, selectedValues[openType])
    const newTitleSelectedStatus = { ...titleSelectedStatus, [openType]: isChecked }
    this.setState({ titleSelectedStatus: newTitleSelectedStatus, openType: '' })
  }
  // 点击确定对话框，关闭对话框
  onSave = value => {
    // 关闭菜单栏，移除houseList的overflow: hiden，让房源列表可以滚动
    this.props.checkIsFixed(false)
    // console.log('选中值：', value, this.state.openType)
    const { openType, selectedValues, titleSelectedStatus } = this.state
    const isChecked = this.checkTitleSelected(openType, value)
    const newTitleSelectedStatus = { ...titleSelectedStatus, [openType]: isChecked }
    const newSelectedValues = { ...selectedValues, [openType]: value }
    // 搜集所有条件数据传给houselist组件，发送ajax
    // area/subway
    // rentType
    // price
    // more
    const areaData = newSelectedValues.area
    const key = newSelectedValues.area[0]
    let areaValue
    if (areaData.length === 3) {
      areaValue = areaData[2] === 'null' ? areaData[1] : areaData[2]
    } else if (areaData.length === 2){
      areaValue = areaData[1]
    }
    const filters = {
      [key]: areaValue,
      rentType: newSelectedValues.mode[0],
      price: newSelectedValues.price[0],
      more: newSelectedValues.more.join(',')
    }
    this.props.onFilter(filters)
    // console.log(filters);
    
    this.setState({
      openType: '',
      selectedValues: newSelectedValues,
      titleSelectedStatus: newTitleSelectedStatus
    })
    // const { openType } = this.state
    // this.setState({
    //   openType: '',
    //   selectedValues: {
    //     ...this.state.selectedValues,
    //     [openType]: value
    //   }
    // })
  }
  checkTitleSelected(openType, value) {
    // area长度为3一定有值，有值高亮，或者选中的值为subway也说明进行了操作需要高亮
    let isChecked = false
    if (openType === 'area' && (value[0] === 'subway' || value.length === 3)) {
      // 区域，有值高亮
      isChecked = true
    } else if (openType === 'mode' && value[0] !== 'null') {
      // 方式，有值高亮
      isChecked = true
    } else if (openType === 'price' && value[0] !== 'null') {
      // 租金，有值高亮
      isChecked = true
    } else if (openType === 'more') {
      // 筛选，有值高亮
    } else {
      // 没有值，没有值不高亮
      isChecked = false
    }
    return isChecked
  }
  async getHouseConditions() {
    const { value } = await getCurrentCity()
    const { data: { body } } = await API.get('/houses/condition', {
      params: {
        id: value
      }
    })
    // console.log(body);
    this.setState({
      houseCoditions: body
    })
  }
  // 渲染FilterPick组件
  renderFilterPicker() {
    // console.log(this.state);
    
    const {
      openType,
      houseCoditions: { area, subway, rentType, price },
      selectedValues
    } = this.state
    // console.log('houseCoditions', area, subway, rentType, price);
    
    if (openType !== 'area' && openType !== 'mode' && openType !== 'price') return null
    // data 表示 数据源
    // cols 表示 列数
    // defaultValues 表示 默认选中值
    let data, cols = 1, defaultValues = selectedValues[openType]
    // console.log(data, cols, defaultValues);
    
    switch (openType) {
      case 'area':
        data = [area, subway]
        cols = 3
        break
      case 'mode':
        data = rentType
        break
      case 'price':
        data = price
        break
      default:
        // 如果不符合预期的情况下，就可以通过 throw 来手动抛出异常
        throw new Error('Invalid type, expected [area, mode, price]~')
    }
    return (
      <FilterPicker
        onClose={this.onClose}
        onSave={this.onSave}
        data={data}
        cols={cols}
        defaultValues={defaultValues}
        openType={openType}
      />
    )
  }
  renderFilterMore() {
    const { openType, 
      houseCoditions:{
        roomType,
        oriented,
        floor,
        characteristic
      },
    selectedValues } = this.state
    // console.log('selectedValues', selectedValues);
    const data = { roomType, oriented, floor, characteristic}
    if (openType !== 'more') return null
    // checkIsFixed={() => this.props.checkIsFixed(false)} onClose={() => this.setState({ openType: '' })} 
    return <FilterMore onClose={this.onClose} data={data} onSave={this.onSave} defaultValues={selectedValues[openType]}></FilterMore>
  }
  renderMask = () => {
    const {openType} = this.state
    // {
    // openType === 'area' || openType === 'mode' || openType === 'price' ? (
    //   <div className={styles.mask} onClick={this.onClose} />
    // ) : null
    // }
    const isShow = openType === 'area' || openType === 'mode' || openType === 'price'
    return (
      // Spring组件实现样式过渡， 此处为遮罩层透明度过渡
      // The optional from-prop only plays a role when the component renders first, 
      // use the to-prop to update the spring with new values.
      <Spring config={config.slow} from={{ opacity: 0 }} to={{ opacity: isShow ? 1 : 0}}>
        {props => {
          if (!props.opacity) return null
          return <div style={props} className={styles.mask} onClick={this.onClose} />        
        }}
      </Spring>
    )
  }
  componentDidMount() {
    this.getHouseConditions()
  }
  render() {
    const { titleSelectedStatus } = this.state
    return (
      <div className={styles.root}>
        {/* 前三个菜单的遮罩层 */}
        {/* {openType === 'area' || openType === 'mode' || openType === 'price' ? (
          <div className={styles.mask} onClick={this.onClose} />
        ) : null} */}
        {this.renderMask()}

        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle
            selected={titleSelectedStatus}
            onClick={this.onTitleClick}
          />

          {/* 前三个菜单对应的内容： */}
          {/* {openType === 'area' || openType === 'mode' || openType === 'price' ? (
              <FilterPicker onClose={this.onClose} onSave={this.onSave} />
            ) : null} */}
          {this.renderFilterPicker()}

          {/* 最后一个菜单对应的内容： */}
          {this.renderFilterMore()}
        </div>
      </div>
    )
  }
}
